#include "simplefoccontroller.h"
#include "simplefocprotocol.h"
#include "serialport.h"

SimpleFOCController::SimpleFOCController(QObject *parent)
    : BaseModule (parent)
{

}

SimpleFOCController::~SimpleFOCController()
{

}

bool SimpleFOCController::setConfig(int id, QVariant &var)
{
    QMutexLocker locker(m_mutex);
    switch (id)
    {
        case ModuleConfigID_SetPortConfig:
            m_port->setConfig(var);
        break;
        case ModuleConfigID_SetProtocolConfig:
//            m_protocol->setProtocolConfig(var);
        break;
        default:
            BaseModule::setConfig(id, var);
        break;
    }
    return true;
}

bool SimpleFOCController::getConfig(int id, QVariant &var)
{
    QMutexLocker locker(m_mutex);
    switch (id)
    {
        case ModuleConfigID_GetPortConfig:
//            m_port->getConfig(var);
        break;
        case ModuleConfigID_GetProtocolConfig:
//            m_protocol->setProtocolConfig(var);
        break;
        default:
            BaseModule::getConfig(id, var);
        break;
    }
    return true;
}

void SimpleFOCController::setPort(BasePort *port)
{
    QMutexLocker locker(m_mutex);
    if (port == nullptr || m_port == port)
        return;

    m_port = port;

    connect(port, &BasePort::receivePackets,
            this, &SimpleFOCController::onParse, Qt::QueuedConnection);
    connect(this, &SimpleFOCController::requestSend,
            port, &BasePort::onSend, Qt::QueuedConnection);
}

BasePort *SimpleFOCController::getPort(void)
{
    QMutexLocker locker(m_mutex);
    return m_port;
}

void SimpleFOCController::setProtocol(BaseProtocol *protocol)
{
    QMutexLocker locker(m_mutex);
    if (protocol == nullptr || m_protocol == protocol)
        return;

    if (m_protocol)
    {
        m_protocol->disconnect();
        m_protocol->deleteLater();
    }
    m_protocol = protocol;
    connect(m_protocol, &BaseProtocol::requestSend, this, &SimpleFOCController::requestSend);
}

BaseProtocol *SimpleFOCController::getProtocol()
{
    QMutexLocker locker(m_mutex);
    return m_protocol;
}

void SimpleFOCController::onParse(QList<ProtocolPacket> packets)
{
    QMutexLocker locker(m_mutex);
    m_protocol->onWork(packets);
}

void SimpleFOCController::onStart()
{
    QMutexLocker locker(m_mutex);
}
